package cn.com.KnowNews.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBConn {
	private static DataSource ds;

	static {
		ds = new ComboPooledDataSource("mysql");
	}

	public static Connection getConnection() {
		Connection connection = null;

		try {
			connection = ds.getConnection();
		} catch (SQLException throwable) {
			throwable.printStackTrace();
		}

		return connection;
	}

	public static void release(PreparedStatement preparedStatement, Connection connection) {
		if (preparedStatement != null) {
			try {
				preparedStatement.close();
			} catch (SQLException throwable) {
				throwable.printStackTrace();
			}
			preparedStatement = null;
		}
		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException throwable) {
				throwable.printStackTrace();
			}
			connection = null;
		}
	}

	public static void release(ResultSet resultSet, PreparedStatement preparedStatement, Connection connection) {
		if (resultSet != null) {
			try {
				resultSet.close();
			} catch (SQLException throwable) {
				throwable.printStackTrace();
			}
			resultSet = null;
		}
		release(preparedStatement, connection);
	}
}
